<template>
    <div class="face-container">
        <div class="face-warp">
            <ul class="divider">
                <li class="left">
                    <div class="line-wrap">
                        <div :class="['line', {'stop': stop}] "></div>
                    </div>
                    <div class="border1"></div>
                    <div class="border2"></div>
                    <video id="video" width="300" height="300" ref="video" autoplay></video>
                    <canvas style="display:none;" id="canvas" width="300" height="300" ref="canvas"></canvas>
                </li>
                <!--                <li class="centent">-->
                <!--                    <el-button type="primary" @click="onclick" ref="facebtn"><div class="btn">确定并提交</div></el-button>-->
                <!--                    <el-button type="primary">重试</el-button>-->
                <!--                </li>-->
                <li class="right">
                    <h1>使用说明</h1>
                    <p>
                        视频活体检测产品，是由两个接口组合而成，主要用于在H5场景下，通过用户新录制并上传一个视频，来进行活体检测的判断。相对于APP有动作校验+静默图片活体、静默图片活体这两种方式，H5视频活体方案比APP方案更加灵活，同时比单张图片活体方式更加安全。
                    </p>
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
    import { faceLogin } from "../../api/face";
    import { setToken, setUserInfo } from "../../common/js/cache";
    import { searchUserInfo } from "../../api/login";
    import { ERROR_NO } from "../../util/config";

    export default {
        data () {
            return {
                stop: false
            }
        },
        methods: {
            _searchUserInfo(id) {
                searchUserInfo(id).then(res => {
                    if (res.code === ERROR_NO) {
                        setUserInfo(res.data.userInfo)
                    }
                })
            },
        },
        mounted () {
            const canvas = this.$refs.canvas
            const video = this.$refs.video
            const context = canvas.getContext('2d')
            let mediaStreamTrack = null
            if (navigator.mediaDevices === undefined) {
                navigator.mediaDevices = {}
            }
            // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
            // 使用getUserMedia，因为它会覆盖现有的属性。
            // 这里，如果缺少getUserMedia属性，就添加它。
            if (navigator.mediaDevices.getUserMedia === undefined) {
                navigator.mediaDevices.getUserMedia = function (constraints) {
                    // 首先获取现存的getUserMedia(如果存在)
                    const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
                    // 有些浏览器不支持，会返回错误信息
                    // 保持接口一致
                    if (!getUserMedia) {
                        return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                    }
                    //否则，使用Promise将调用包装到旧的navigator.getUserMedia
                    return new Promise(function (resolve, reject) {
                        getUserMedia.call(navigator, constraints, resolve, reject);
                    })
                }
            }
            const constraints = {audio: false, video: {width: 300, height: 300}}
            navigator.mediaDevices.getUserMedia(constraints)
                .then(function (stream) {
                    const video = document.querySelector('video');
                    // 旧的浏览器可能没有srcObject
                    if ("srcObject" in video) {
                        video.srcObject = stream;
                    } else {
                        //避免在新的浏览器中使用它，因为它正在被弃用。
                        video.src = window.URL.createObjectURL(stream);
                    }
                    mediaStreamTrack = stream.getTracks()[0]
                    video.onloadedmetadata = function (e) {
                        console.log(e)
                        video.play()
                    }
                })
                .catch(function (err) {
                    console.log(err.name + ": " + err.message)
                })
            // const btn = document.getElementsByClassName('btn')[0]
            this.timer = setInterval(() => {
                // 点击，canvas画图
                context.drawImage(video, 0, 0, 300, 300);
                // 获取图片base64链接
                var image = canvas.toDataURL('image/png');

                // base64转文件
                function dataURLtoFile (dataurl, filename) {
                    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                    while ( n-- ) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new File([u8arr], filename, {type: mime});
                }

                const file = dataURLtoFile(image, 'aa.png')
                const formData = new FormData()
                formData.set('file', file)
                faceLogin(formData).then(res => {
                    if (res.code === 200) {
                        clearInterval(this.timer)
                        const token = res.data.userInfo.Token
                        setToken(token)
                        this._searchUserInfo(res.data.userInfo.userId)
                        this.$message({
                            message: '人脸识别成功',
                            type: 'success'
                        });
                        setTimeout(() => {
                            mediaStreamTrack.stop()
                            mediaStreamTrack = null
                            this.$router.push('/home')
                        }, 2000)
                        return
                    }
                    if (this.time) {
                        clearTimeout(this.time)
                    }
                    this.time = setTimeout(() => {
                        this.$message({
                            message: '请对准屏幕',
                            duration: 500
                        })
                    }, 1000)
                })
            }, 1000)
            // btn.addEventListener("click", function () {
            //     // 点击，canvas画图
            //     context.drawImage(video, 0, 0, 705, 705);
            //     // 获取图片base64链接
            //     var image = canvas.toDataURL('image/png');
            //     // base64转文件
            //     function dataURLtoFile(dataurl, filename) {
            //         var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            //             bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            //         while (n--) {
            //             u8arr[n] = bstr.charCodeAt(n);
            //         }
            //         return new File([u8arr], filename, {type: mime});
            //     }
            //     const file = dataURLtoFile(image, 'aa.png')
            //     const formData = new FormData()
            //     formData.set('file', file)
            //     faceLogin(formData).then(res => {
            //         console.log(res)
            //     })
            // })
            // setTimeout(() => {
            //     this.$notify({
            //         title: '提示',
            //         message: '登陆成功',
            //         type: 'succeess',
            //         duration: 1500
            //     })
            //     setTimeout(() => {
            //         this.$router.push('/home')
            //     }, 100)
            //     this.stop = true
            // }, 5000)
        },
        beforeDestroy () {
            this.mediaStreamTrack && this.mediaStreamTrack.stop()
            // this.mediaStreamTrack = null
        }
    }
</script>

<style scoped lang="scss">
    .face-container {
        min-width: 1200px;
        min-height: 900px;
        overflow: auto;
        position: fixed;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: url("../../assets/images/face.jpg") no-repeat;
        background-size: cover;

        .face-warp {
            position: fixed;
            top: 10%;
            right: 10%;
            left: 10%;
            bottom: 10%;
            border-radius: 20px;
            background-color: rgba(28, 57, 118, 0.32);

            .divider {
                width: 100%;
                height: 100%;
                display: flex;
                justify-content: space-around;
                align-items: center;

                .left {
                    position: relative;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 405px;
                    height: 405px;
                    border-radius: 3px;
                    box-sizing: border-box;

                    .line-wrap {
                        position: absolute;
                        z-index: 999;
                        width: 300px;
                        height: 300px;
                        overflow: hidden;

                        .line {
                            position: relative;
                            z-index: 999;
                            height: calc(100% - 2px);
                            width: 100%;
                            background: linear-gradient(180deg, rgba(0, 255, 51, 0) 43%, #558DE3 211%);
                            border-bottom: 3px solid #558DE3;
                            transform: translateY(-100%);
                            animation: radar-beam 2s infinite;
                            animation-timing-function: cubic-bezier(0.53, 0, 0.43, 0.99);
                            animation-delay: 1.4s;
                        }

                        .stop {
                            animation-play-state: paused;
                        }
                    }

                    &::before {
                        content: "";
                        width: 86px;
                        height: 86px;
                        position: absolute;
                        top: 0;
                        right: 0;
                        border: 3px solid transparent;
                        border-right-color: #fff;
                        border-top-color: #fff;
                    }

                    &::after {
                        content: "";
                        width: 86px;
                        height: 86px;
                        position: absolute;
                        bottom: 0;
                        right: 0;
                        border: 3px solid transparent;
                        border-right-color: #fff;
                        border-bottom-color: #fff;
                    }

                    .border1 {
                        width: 86px;
                        height: 86px;
                        position: absolute;
                        top: 0;
                        left: 0;
                        border: 3px solid transparent;
                        border-left-color: #fff;
                        border-top-color: #fff;
                    }

                    .border2 {
                        width: 86px;
                        height: 86px;
                        position: absolute;
                        bottom: 0;
                        left: 0;
                        border: 3px solid transparent;
                        border-left-color: #fff;
                        border-bottom-color: #fff;
                    }
                }

                .centent {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    column-gap: 40px;

                    ::v-deep .el-button {
                        width: 180px;
                        height: 54px;
                        line-height: 20px;
                        border-radius: 20px;
                        background-color: rgba(85, 141, 227, 1);
                        margin-left: 0;
                        margin-top: 20px;
                    }
                }

                .right {
                    max-width: 346px;
                    overflow: hidden;
                    color: rgba(255, 255, 255, 100);

                    h1 {
                        text-align: center;
                        font-size: 36px;
                        margin-bottom: 20px;
                    }

                    p {
                        font-size: 20px;
                    }
                }
            }
        }
    }

    @keyframes radar-beam {
        0% {
            transform: translateY(-100%);
        }

        100% {
            transform: translateY(0);
        }
    }
</style>
